class CategoriesController < ApplicationController
  caches_page :show
  cache_sweeper :record_sweeper, :only => [:create, :update, :destroy]
  before_filter :require_admin, :except => :show
  before_filter :find_or_initialize_category, :except => [:index, :create]
#  after_filter :expire_fragment_cache, :only => [:create, :update, :destroy]
  # GET /categories
  # GET /categories.xml
  def index
    @categories = Category.all

    respond_to do |format|
      format.html # index.html.erb
      format.xml  { render :xml => @categories }
    end
  end

  # GET /categories/1
  # GET /categories/1.xml
  def show
    @posts = @category.posts.find(:page => params[:page])
    @title = @category.name
    @description = @category.name
    respond_to do |format|
      format.html { render :layout => 'application' }# show.html.erb
      format.xml  { render :xml => @category }
    end
  end

  # GET /categories/new
  # GET /categories/new.xml
  def new
    respond_to do |format|
      format.html # new.html.erb
      format.xml  { render :xml => @category }
    end
  end

  # GET /categories/1/edit
  def edit

  end

  # POST /categories
  # POST /categories.xml
  def create
    @category = Category.new(params[:category])

    respond_to do |format|
      if @category.save
        format.html { redirect_to(@category, :notice => '栏目创建成功!') }
        format.xml  { render :xml => @category, :status => :created, :location => @category }
      else
        format.html { render :action => "new" }
        format.xml  { render :xml => @category.errors, :status => :unprocessable_entity }
      end
    end
  end

  # PUT /categories/1
  # PUT /categories/1.xml
  def update
    respond_to do |format|
      if @category.update_attributes(params[:category])   
        format.html { redirect_to(@category, :notice => '栏目更新成功!') }
        format.xml  { head :ok }
      else
        format.html { render :action => "edit" }
        format.xml  { render :xml => @category.errors, :status => :unprocessable_entity }
      end
    end
  end

  # DELETE /categories/1
  # DELETE /categories/1.xml
  def destroy
    @category.destroy

    respond_to do |format|
      format.html { redirect_to(categories_url) }
      format.xml  { head :ok }
    end
  end

  private
  def find_or_initialize_category
    @category = params[:id] ? Category.find(params[:id]) : Category.new
  end

  # => 清除右侧目录树片段的缓存
  def expire_fragment_cache
    expire_fragment(RecordSweeper::PATH.merge(:action_suffix => 'category_tree'))
  end
end
